<?php
/**
 * Created by PhpStorm.
 * User: xpz
 * Date: 2021/5/26
 * Time: 9:44
 */

namespace app\api\controller;

use app\common\controller\Api;
use fast\Encrypt;
use think\Db;

class Question extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $model = null;
    protected $letter = ["A","B","C","D","E","F"];
    protected $bgcolor = ["#cccccc","","#cccccc","","#cccccc",""];
    protected $type = ["","单选","多选","判断"];

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = model('app\common\model\Question');

    }



    public function index($category){
        $rs = collection($this->model->field("answer,title,id,type")->where(['subject'=>$category,'status'=>1])->order("id desc")->select())->toArray();
        if(!empty($rs)){
            foreach($rs as $k=>$v){
                $answer = json_decode($v['answer']);
                $rs[$k]['your_answer'] = '';
                $rs[$k]['type'] = $this->type[$v['type']];
                $okAnswer = 0;
                $tempAnswer = [];
                foreach($answer as $key=>$val){
                    $valArr = explode("###",$val);
                    $temp['sort'] = $this->letter[$key];
                    $temp['content'] = $valArr[0];
                    $temp['is_ok'] = $valArr[1];
                    $temp['id'] = $key+1;
                    $temp['bgclass'] = $this->bgcolor[$key];
                    if($valArr[1] == 1){
                        $okAnswer = $temp['id'];
                    };
                    $tempAnswer[] = $temp;
                }
                $rs[$k]['answer'] = $tempAnswer;
                $rs[$k]['ok_answer'] = $okAnswer;
            }
        }
        $this->success('请求成功',$rs);
    }

    public function addmyanswer($content,$openid,$categoryid){
        $answerArr = [];
        $answerIdArr = [];
        if(empty($content)){
            $this->error("内容不能为空！");
        }
        if(empty($openid)){
            $this->error("请先登录！");
        }
        if(empty($categoryid)){
            $this->error("科目不能为空！");
        }
        $contentArr = explode('-',$content);
//        print_r($contentArr);exit;
        if(!empty($contentArr) && count($contentArr) > 0){
            foreach($contentArr as $k=>$v){
                if(!empty($v)){
                    $answerTempArr = explode("_",$v);
                    $answerArr[$answerTempArr[0]] = $answerTempArr[1];
                    $answerIdArr[] = $answerTempArr[0];
                }

            }
        }
        if(empty($answerArr)){
            $this->error("内容解析不正确！");
        }

        $subjectInfo = model('Subject')->where(['id'=>$categoryid])->find();
        if(empty($subjectInfo['id'])){
            $this->error("科目不存在！");
        }
        $questionArr = collection(model('Question')->whereIn('id',$answerIdArr)->select())->toArray();
        if(empty($questionArr)){
            $this->error("问题不存在！");
        }

        $userId = $this->getUserId($openid);
//        var_dump($userId);exit;
        if(empty($userId)){
            $this->error("登录状态不正确！");
        }


        Db::startTrans();


        $time = time();

        $myAnsweredId = model('MyAnswered')->insertGetId(['title'=>$subjectInfo['name']."-".date('Y-m-d H:i:s',$time),'user_id'=>$userId,"add_time"=>$time]);
//        var_dump($myAnsweredId);
        $result = [];

        foreach($questionArr as $k=>$v){
            $tempArr = [];
            $tempArr['user_id']= $userId;
            $tempArr['title']= $v['title'];
            $tempArr['question_id']= $v['id'];
            $tempArr['subject']= $v['subject'];
            $tempArr['subject_name']= $v['subject_name'];
            $tempArr['type']= $v['type'];
            $tempArr['your_answer']= $answerArr[$v['id']];
            $tempArr['answer'] = $v['answer'];
            $tempArr['add_time'] = $time;
            $tempArr['my_answered_id'] = $myAnsweredId;

            $result[] = $tempArr;
        }

        $addRs2 = model("UserQuestion")->insertAll($result);


        try{
            if(!empty($myAnsweredId) && !empty($addRs2)){
                // 提交事务
                Db::commit();
                $this->success("提交成功！");
            } else {
                // 回滚事务
                Db::rollback();
                $this->error("提交失败！1");
            }
        } catch (Exception $e){
            // 回滚事务
            Db::rollback();
            $this->error("提交失败！2");
        }
//        print_r($result);
    }

    /**
     * @param $openid
     * @return string
     */
    private function getUserId($openid){
        $userId = "";
        $openIdString = Encrypt::decrypt($openid);
//        echo $openIdString;exit;
        if(!empty($openid)){
            $openIdArr = explode('_',$openIdString);
//            print_r($openIdArr);exit;
//            if(count($openIdArr) != 2){
//                return $openIdArr[1];
//            }
            $userId = $openIdArr[count($openIdArr)-1];
        }
        return $userId;
    }
}